/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.web.web;

import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.jwt.JwtTokenUtil;
import com.jeeplus.common.utils.redis.RedisKeys;
import com.jeeplus.common.utils.redis.RedisUtil;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.web.entity.YjPersonLogin;
import com.jeeplus.modules.web.entity.YjSalesman;
import com.jeeplus.modules.web.model.WxLoginModel;
import com.jeeplus.modules.web.model.WxLoginTypeEnum;
import com.jeeplus.modules.web.service.YjDistrictService;
import com.jeeplus.modules.web.service.YjSalesmanService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Map;

/**
 * 用户Controller
 * @author rongjie
 * @version 2017-08-06
 */
@Controller
@RequestMapping(value = "${adminPath}/web/salesman")
public class YjSalesmanController extends BaseController {

	@Autowired
	private YjSalesmanService yjSalesmanService;

	@Autowired
	private YjDistrictService yjDistrictService;

	@Autowired
	private RedisUtil redisUtil;

	@ModelAttribute
	public YjSalesman get(@RequestParam(required=false) String id) {
		YjSalesman entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = yjSalesmanService.get(id);

			// 拆分省市区region
			String region = entity.getArea();
			if (StringUtils.isNotBlank(region)) {
				String[] parts = region.split(" ");
				if (parts.length >= 3) {
					entity.setProvince(parts[0]);
					entity.setCity(parts[1]);
					entity.setDistrict(parts[2]);
				}
			}
		}
		if (entity == null){
			entity = new YjSalesman();
		}
		return entity;
	}
	
	/**
	 * 用户列表页面
	 */
	@RequiresPermissions("web:yjSalesman:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/web/yjSalesmanList";
	}
	
	/**
	 * 用户列表数据
	 */
	@ResponseBody
	@RequiresPermissions("web:yjSalesman:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(YjSalesman yjSalesman, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<YjSalesman> page = yjSalesmanService.findPage(new Page<YjSalesman>(request, response), yjSalesman);
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑用户表单页面
	 */
	@RequiresPermissions(value={"web:yjSalesman:view","web:yjSalesman:add","web:yjSalesman:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(YjSalesman yjSalesman, Model model) {
		model.addAttribute("yjSalesman", yjSalesman);
		if(StringUtils.isBlank(yjSalesman.getId())){//如果ID是空为添加
			model.addAttribute("isAdd", true);
		}
		return "modules/web/yjSalesmanForm";
	}

	/**
	 * 保存用户
	 */
	@RequiresPermissions(value={"web:yjSalesman:add","web:yjSalesman:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(YjSalesman yjSalesman, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, yjSalesman)){
			return form(yjSalesman, model);
		}

		//省市区
		if (StringUtils.isNotBlank(yjSalesman.getProvince()) && StringUtils.isNotBlank(yjSalesman.getCity()) && StringUtils.isNotBlank(yjSalesman.getDistrict())) {
			StringBuffer regionSb = new StringBuffer();
			regionSb.append(yjSalesman.getProvince()).append(" ");
			regionSb.append(yjSalesman.getCity()).append(" ");
			regionSb.append(yjSalesman.getDistrict());

			yjSalesman.setArea(regionSb.toString());
		}

		//新增或编辑表单保存
		boolean isDuplicate = checkDuplicate(yjSalesman);
		if (isDuplicate) {
			addMessage(model, "保存失败！该业务员已经创建过");
			return form(yjSalesman, model);
		}

		yjSalesmanService.save(yjSalesman);//保存
		addMessage(redirectAttributes, "保存用户成功");
		return "redirect:"+Global.getAdminPath()+"/web/salesman/?repage";
	}
	
	/**
	 * 删除用户
	 */
	@ResponseBody
	@RequiresPermissions("web:yjSalesman:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(YjSalesman yjSalesman, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		yjSalesmanService.delete(yjSalesman);
		j.setMsg("删除用户成功");
		return j;
	}
	
	/**
	 * 批量删除用户
	 */
	@ResponseBody
	@RequiresPermissions("web:yjSalesman:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
//		for(String id : idArray){
//			yjSalesmanService.delete(yjSalesmanService.get(id));
//		}
		yjSalesmanService.batchDeleteByLogic(Arrays.asList(idArray));
		j.setMsg("删除用户成功");
		return j;
	}

	/**
	 * 导出excel文件
	@ResponseBody
	@RequiresPermissions("web:yjSalesman:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(YjSalesman yjSalesman, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "用户"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<YjSalesman> page = yjSalesmanService.findPage(new Page<YjSalesman>(request, response, -1), yjSalesman);
    		new ExportExcel("用户", YjSalesman.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出用户记录失败！失败信息："+e.getMessage());
		}
			return j;
    }*/

	/**
	 * 导入Excel数据

	@RequiresPermissions("web:yjSalesman:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<YjSalesman> list = ei.getDataList(YjSalesman.class);
			for (YjSalesman yjSalesman : list){
				try{
					yjSalesmanService.save(yjSalesman);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条用户记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条用户记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入用户失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/web/yjSalesman/?repage";
    }*/
	
	/**
	 * 下载导入用户数据模板
	@RequiresPermissions("web:yjSalesman:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "用户数据导入模板.xlsx";
    		List<WxUser> list = Lists.newArrayList(); 
    		new ExportExcel("用户数据", WxUser.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/web/yjSalesman/?repage";
    }*/

	/**
	 * 业务员登录
	 * @param yjSalesmanLogin 业务员登录实体类
	 * @return
	 */
	@ResponseBody
	@PostMapping(value = "login")
	public AjaxJson login(@Validated @RequestBody YjPersonLogin yjSalesmanLogin) throws Exception {
		AjaxJson j = new AjaxJson();

		// 直接检查token是否有效
		if (StringUtils.isNotBlank(yjSalesmanLogin.getToken())) {
			//String redisToken = redisUtil.get(RedisKeys.salesmanLoginToken(yjSalesmanLogin.getPhoneNumber()));
			WxLoginModel loginModel = JwtTokenUtil.getAppLoginModel(yjSalesmanLogin.getToken());
			if (loginModel == null) {
				j.setSuccess(false);
				j.setMsg("token无效！");
				return j;
			}

			// 登录的类型不是业务员
			if (loginModel.getType() != WxLoginTypeEnum.SALESMAN) {
				j.setSuccess(false);
				j.setMsg("token无效！");
				return j;
			}

			//j.getBody().put("data", redisToken);
		} else {
			String phoneNumber = yjSalesmanLogin.getPhoneNumber();
			String captcha = yjSalesmanLogin.getCaptcha();

			if (StringUtils.isBlank(phoneNumber)) {
				j.setSuccess(false);
				j.setMsg("手机号不能为空");
				return j;
			}

			// 检查手机号是否有效
			YjSalesman record = new YjSalesman();
			record.setPhoneNumber(phoneNumber);
			Long count = yjSalesmanService.count(record);
			if (count == 0L) {
				j.setSuccess(false);
				j.setMsg("手机号不存在！");
				return j;
			}

			if (StringUtils.isBlank(captcha)) {
				j.setSuccess(false);
				j.setMsg("验证码不能为空");
				return j;
			}

			// 检查验证码是否有效
			// 2021-06-18 审核用测试账号追加
			String testSalesmanPhoneNumber = Global.getConfig("testSalesmanPhoneNumber");
			String testSalesmanCaptcha = Global.getConfig("testSalesmanCaptcha");
			if (StringUtils.isNotBlank(testSalesmanPhoneNumber) && phoneNumber.equals(testSalesmanPhoneNumber))
			{
				if (!captcha.equals(testSalesmanCaptcha)){
					j.setSuccess(false);
					j.setMsg("验证码无效");
					return j;
				}
			} else {
				String redisCaptcha = redisUtil.get(RedisKeys.salesmanLoginCaptcha(phoneNumber));
				if (StringUtils.isBlank(redisCaptcha)) {
					j.setSuccess(false);
					j.setMsg("验证码无效");
					return j;
				}

				// 验证码不一致
				if (!captcha.equals(redisCaptcha)) {
					j.setSuccess(false);
					j.setMsg("验证码不正确");
					return j;
				}
			}

			// 设置token 有效期24小时
			String token = JwtTokenUtil.createToken(new WxLoginModel(phoneNumber, WxLoginTypeEnum.SALESMAN));
			j.getBody().put("data", token);
		}

		// 验证码一致，登录成功
		j.setSuccess(true);
		j.setMsg("登录成功");
		return j;
	}

	/**
	 * 检查是否重复
	 * @param yjSalesman
	 * @return
	 */
	private boolean checkDuplicate(YjSalesman yjSalesman) {
		YjSalesman record = new YjSalesman();
		record.setSalesmanName(yjSalesman.getSalesmanName());
		record.setPhoneNumber(yjSalesman.getPhoneNumber());

		if (StringUtils.isNotBlank(yjSalesman.getId())) {
			record.setId(yjSalesman.getId());
		}

		return yjSalesmanService.isDuplicate(record);
	}
}